define([
    'jquery',
    'signin',
    'jquery-cookie'
], function ($, signin) {

    // 加载cookie中要加入购物车的商品
    function goodsDownload() {
        let baseUrl = signin.getBaseUrl(); //获取基础地址
        let userInfo = null;
        signin.checkUserInfo() == null ? '' : userInfo = JSON.parse(signin.checkUserInfo()); //获取用户信息

        let cookieArr = null;
        let data = []; //取出所有商品id放进数组
        if ($.cookie("goods")) {
            let cookieStr = $.cookie("goods"); //获取cookie中商品信息
            cookieArr = JSON.parse(cookieStr); //转对象
            cookieArr.forEach(function (item) {
                data.push(item.goodsId)
            });
        }

        //判断用户是否登录
        if (userInfo) {
            //登录状态 
            //登录状态并且未登录前有加入购物车的产品
            $.get(baseUrl + "/cart/lists", {
                    userId: userInfo.id
                },
                function (res) {
                    // console.log(res);
                    // showCartGoods(res.data);
                    res.data.forEach(function (item) {
                        // console.log(item);
                        let node = $(`                  
                        <tr data-cartId="${item.id}" data-goodsId="${item.goodsId}">
                        <td class="col0 "><input type="checkbox" value="" class="sel"></td>
                        <td class="col1"><a href=""><img src="${item.goods.goodsThumb}" alt="" /></a>  <strong><a href="">${item.goods.goodsName}</a></strong></td>
                        <td class="col2"> <p>颜色：073深红</p> <p>尺码：170/92A/S</p> </td>
                        <td class="col3">￥<span>${item.goods.shopPrice}</span></td>
                        <td class="col4"> 
                            <a href="javascript:;" class="reduce_num"></a>
                            <input type="text" name="amount" value="${item.goodsCount}" class="amount"/>
                            <a href="javascript:;" class="add_num"></a>
                        </td>
                        <td class="col5">￥<span>${parseFloat(item.goods.shopPrice*item.goodsCount).toFixed(2)}</span></td>
                        <td class="col6"><a href="" class="del">删除</a></td>
                    </tr>
                        `);
                        $(".mycart").find("table tbody").append(node);
                    });
                });
        } else {
            // 未登录状态
            $.post(baseUrl + "/goods/getGoodsByIds", {
                    goodsIds: data
                },
                function (res) {
                    if (cookieArr) {
                        let newGoodsArr = []; //取出id和cookie中id相同的商品信息
                        for (let i = 0; i < cookieArr.length; i++) {
                            for (let j = 0; j < res.data.length; j++) {
                                if (cookieArr[i].goodsId == res.data[j].id) {
                                    //获取cookie中商品的数量
                                    res.data[j].num = cookieArr[i].num;
                                    newGoodsArr.push(res.data[j]);
                                }
                            }
                        }
                        for (let j = 0; j < newGoodsArr.length; j++) {
                            let node = $(`                  
                        <tr data-goodsId="${newGoodsArr[j].id}">
                        <td class="col0 "><input type="checkbox" value="" class="sel"></td>
                        <td class="col1"><a href=""><img src="${newGoodsArr[j].goodsThumb}" alt="" /></a>  <strong><a href="">${newGoodsArr[j].goodsName}</a></strong></td>
                        <td class="col2"> <p>颜色：073深红</p> <p>尺码：170/92A/S</p> </td>
                        <td class="col3">￥<span>${newGoodsArr[j].shopPrice}</span></td>
                        <td class="col4"> 
                            <a href="javascript:;" class="reduce_num"></a>
                            <input type="text" name="amount" value="${newGoodsArr[j].num}" class="amount"/>
                            <a href="javascript:;" class="add_num"></a>
                        </td>
                        <td class="col5">￥<span>${parseFloat(newGoodsArr[j].shopPrice*newGoodsArr[j].num).toFixed(2)}</span></td>
                        <td class="col6"><a href="" class="del">删除</a></td>
                    </tr>
                        `);
                            $(".mycart").find("table tbody").append(node);
                        }
                    }
                });
        }
    }

    // 购物车加减删除
    function changeCart() {

        // 获取当前商品的id 购物车id
        let userInfo = null;
        let cookieArr = null;
        if ($.cookie("goods")) {
            let cookieStr = $.cookie("goods");
            cookieArr = JSON.parse(cookieStr); //转对象
        }
        let baseUrl = signin.getBaseUrl(); //获取基础地址

        signin.checkUserInfo() == null ? '' : userInfo = JSON.parse(signin.checkUserInfo()); //获取用户信息

        // +-点击事件//改变购物车数量 cookie中数量
        $(".mycart table tbody").on("click", "tr .reduce_num,.add_num", function () {

            let goodsId = $(this).parent("td").parent("tr").attr("data-goodsId"); //商品id
            let cartId = $(this).parent("td").parent("tr").attr("data-cartId"); //购物车id
            let goodsCount = $(this).siblings("input").val();
            console.log(goodsId, cartId);
            if (userInfo) {
                //已登录
                if (this.className == "reduce_num") {
                    goodsCount == 1 ? alert("数量已经为1，不能再减少！") : goodsCount--;
                } else {
                    goodsCount++;
                }
                $(this).siblings("input").val(goodsCount);
                //单价
                let price = $(this).parent("td").siblings('.col3').find("span").html().trim();
                //小计
                let totalObj = $(this).parent("td").siblings(".col5").find("span");
                totalObj.html((price * goodsCount).toFixed(2) + "元");

                //传回数据库
                $.post(baseUrl + "/cart/change", {
                        userId: userInfo.id,
                        cartId: cartId,
                        goodsId: goodsId,
                        goodsCount: goodsCount

                    },
                    function (res) {
                        if (res != 0) {
                            console.log(res.msg);
                            return false;
                        }
                        console.log(res);
                    });

            } else {
                // 没有登录
                for (let i = 0; i < cookieArr.length; i++) {
                    if (cookieArr[i].goodsId == goodsId) {
                        if (this.className == "reduce_num") {
                            cookieArr[i].num == 1 ? alert("数量已经为1，不能再减少！") : cookieArr[i].num--;
                        } else {
                            cookieArr[i].num++;
                        }
                        $(this).siblings("input").val(cookieArr[i].num);
                        //单价
                        let price = $(this).parent("td").siblings('.col3').find("span").html().trim();
                        //小计
                        let totalObj = $(this).parent("td").siblings(".col5").find("span");
                        totalObj.html((price * cookieArr[i].num).toFixed(2) + "元");

                        //最后将更改后的数据存储到cookie中
                        $.cookie("goods", JSON.stringify(cookieArr), {
                            expires: 7
                        })
                        break;
                    }
                }
            }
            isCheckAll();
            return false;
        });


        //删除事件
        $(".mycart table tbody").on("click", "tr .del", function () {
            let goodsId = $(this).parent("td").parent("tr").attr("data-goodsId"); //商品id
            let cartId = $(this).parent("td").parent("tr").attr("data-cartId"); //购物车id
            let userInfo = null;
            signin.checkUserInfo() == null ? '' : userInfo = JSON.parse(signin.checkUserInfo()); //获取用户信息

            if (userInfo) {
                $.get(baseUrl + "/cart/remove", {
                        cartId: cartId,
                        userId: userInfo.id,
                    },
                    function (res) {

                        if (res.code != 0) {
                            alert(res.msg);
                            return false;
                        }
                        console.log(res);
                        // $(this).parent("td").parent("tr").remove();
                    });

            } else {
                // $(this).parent("td").parent("tr").remove();
                for (let i = 0; i < cookieArr.length; i++) {
                    if (cookieArr[i].goodsId == goodsId) {
                        cookieArr.splice(i, 1); //改变原始数组
                        break;
                    }
                }
                //cookie中没有数据清除cookie还有在放回
                cookieArr.length == 0 ? $.removeCookie('userInfo', {
                    path: '/'
                }) : $.cookie("goods", JSON.stringify(cookieArr), {
                    expires: 7
                });
            }

            $(this).parent("td").parent("tr").remove();
            return false;
        });

        //清除购物车
        $(".cart_btn ").on("click", "button.delAll", function () {
            let userInfo = null;
            signin.checkUserInfo() == null ? '' : userInfo = JSON.parse(signin.checkUserInfo()); //获取用户信息
            if (userInfo) {
                $.get(baseUrl + "/cart/clear", {
                        userId: userInfo.id
                    },
                    function (res) {
                        if (res.code == 1) {
                            alert(res.msg);
                            return false;
                        }
                        console.log(res);
                    },
                    "dataType"
                );
            } else {

                $.removeCookie('goods', {
                    path: '/'
                });

            }
            $(this).parent(".cart_btn").prev("table").children("tbody").find("tr").remove();
            console.log($(this).parent(".cart_btn").prev("table").children("tbody").find("tr"));
            return false;
        });
    }

    //全选和单选
    function isCheck() {
        //全选按钮
        $("table thead").find("input[type=checkbox]").click(function () {
            let allChecks = $("table tbody tr").find("input[type=checkbox]");
            // console.log(allChecks);
            if ($(this).is(":checked")) {
                $(this).add(allChecks).prop("checked", true);
            } else {
                $(this).add(allChecks).prop("checked", false);
            }
            isCheckAll();
        });

        //单个商品
        $("table tbody ").on("click", "input[type=checkbox]", function () {
            if ($(this).is(":checked")) {
                $(this).attr("checked", true);
            } else {
                $(this).attr("checked", false);
                // console.log($(this).is(":checked"));
            }
            isCheckAll();
        });

    }

    //计算购物车总计
    function isCheckAll() {
        //所有商品勾选按钮        
        let allCheckBoxes = $("table tbody ").find("tr");

        let isAll = true, //全选
            totalMoney = 0; //总计
        allCheckBoxes.each(function (index, item) {
            if (!$(item).find("input[type=checkbox]").is(":checked")) {
                isAll = false;
            } else {
                let price = parseFloat($(item).find(".col3>span").html().trim());
                let num = parseInt($(item).find(".col4>input[name=amount]").val());
                totalMoney += price * num;
            }
        });

        //设置总价      
        $("table tfoot tr").find("#total").html(totalMoney.toFixed(2));
        // 全选
        if (isAll) {
            $("table thead").find("input[type=checkbox]").prop("checked", true);
        } else {
            $("table thead").find("input[type=checkbox]").prop("checked", false);
        }
    }

    //结算功能
    function balance() {
        let userInfo = null;
        signin.checkUserInfo() == null ? '' : userInfo = JSON.parse(signin.checkUserInfo()); //获取用户信息

        let selectGoodsArr = []; //选中的商品id

        //全选
        $(".mycart table thead").on("click", "input[type=checkbox]", function () {
            console.log($(this));
            let $this = $(this);
            if ($this.is(":checked")) {

                let goods = $(".mycart table tbody").find("tr");

                console.log(goods)
                goods.each(function () {
                    // console.log($(this).attr("data-cartid"));
                    // console.log($(this).find("input[name=amount]").val());
                    selectGoodsArr.push({
                        goodsId: $(this).attr("data-goodsid"),
                        cartId: $(this).attr("data-cartid"),
                        goodsCount: $(this).find("input[name=amount]").val()
                    });
                });
            } else {
                selectGoodsArr = [];
            }
            console.log(selectGoodsArr);
        });
        //单选
        $(".mycart table tbody").on("click", "input[type=checkbox]", function () {
            // console.log($(this));
            if ($(this).is(":checked")) {
                console.log($(this));
                let goodsId = $(this).parent().parent().attr("data-goodsid");
                let cartId = $(this).parent().parent().attr("data-cartid");
                let goodsCount = $(this).parent().siblings(".col4").children("input[name=amount]").val();
                // console.log($(this).parent().siblings(".col4").children("input[name=amount]").val());
                // console.log(cartId);
                selectGoodsArr.push({
                    goodsId,
                    cartId,
                    goodsCount,
                });
            } else {
                let cartId = $(this).parent().parent().attr("data-cartid");
                selectGoodsArr.splice(selectGoodsArr.indexOf(cartId), 1)
            }
            // console.log(selectGoodsArr);
        });

        // console.log(selectGoodsArr.length);

        //点击去结算
        $(".cart_btn ").on("click", ".checkout", function () {
            console.log(1);
            // 判断用户是否登录
            if (userInfo) {
                location.href = `checkout.html?`;
                selectGoodsArr.length == 0 ? '' : $.cookie("selectGoods", JSON.stringify(selectGoodsArr));
            } else {
                location.href = 'login.html';
                let cartUrl = window.location.href;
                console.log(cartUrl);
                localStorage.setItem("backUrl", window.location.href);
            }
            return false;
        });


    }


    return {
        goodsDownload: goodsDownload,
        changeCart: changeCart,
        isCheck: isCheck,
        balance: balance
    }

});